package com._54programer.demo.hello;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author SN
 * @date 2019/11/28
 * @description
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * @param ctx 上下文对象, 包含管道pipeline、通道channel等
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器线程名: "+Thread.currentThread().getName());
        System.out.println("ctx: "+ctx);
        System.out.println("pipeline: "+ctx.pipeline());
        System.out.println("channel: "+ctx.channel());

        //将msg转为ByteBuf
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("客户端地址: "+ctx.channel().remoteAddress());
        System.out.println("客户端消息: "+buf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 数据读取完毕
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将数据写入缓存并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端!!!", CharsetUtil.UTF_8));
    }

    /**
     * 异常处理, 一般我们会在这里关闭通道
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
